package design.graduation.novelsystem.controller;

import design.graduation.novelsystem.constant.Constant;
import design.graduation.novelsystem.model.dto.ResultObj;
import design.graduation.novelsystem.service.AdminService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * @author: 洪少尉
 * @Date: 2020/4/13 23:42
 * @Description: 后台登录管理
 */
@RestController
@RequestMapping("login")
public class LoginController {
	@Autowired
	private AdminService adminService;
	@Autowired
	private StringRedisTemplate redisTemplate;
	/**
	 * 登录接口
	 */
	@PostMapping("doLogin")
	public ResultObj doLogin(String loginName, String password,String keyCode,String captcha, HttpServletRequest request){
		ValueOperations<String, String> opsForValue = redisTemplate.opsForValue();
		String code = opsForValue.get(keyCode);
		if(null == code) {
			return new ResultObj(Constant.ERROR_CODE, "验证码过期,请重试");
		}
		if (!code.equals(captcha)){
			return new ResultObj(Constant.ERROR_CODE, "验证码错误，请重试");
		}
		try {
			return new ResultObj(Constant.SUCCESS_CODE, "登录成功",adminService.doLogin(loginName,password,request));
		} catch (UnknownAccountException e){
			return new ResultObj(Constant.ERROR_CODE, "当前账户不存在");
		}catch (IncorrectCredentialsException e){
			return new ResultObj(Constant.ERROR_CODE, "密码错误");
		}
	}
	/**
	 * 验证是否登录
	 */
	@PostMapping("checkLogin")
	public ResultObj checkLogin(){
		if(SecurityUtils.getSubject().isAuthenticated()){
			return ResultObj.IS_LOGIN;
		}else{
			return ResultObj.UN_LOGIN;
		}
	}
}
